using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using csvviewer.contracts;

namespace csvviewer.adapter
{
	public class Read_page_lines_from_file
	{
		public void Process(PageOfLinePositions pageOfPositions)
		{
			var pageOfLines = new PageOfLines();
			pageOfLines.PageInfo = pageOfPositions.PageInfo;
			
			var lines = new List<string>();
			
			lines.AddRange(Read_lines(_filename, pageOfPositions.LinePositions.First(), 1));
			lines.AddRange(Read_lines(_filename, pageOfPositions.LinePositions.ElementAt(1), pageOfPositions.LinePositions.Count()-1));
			
			pageOfLines.Lines = lines;
			
			this.Page(pageOfLines);
		}
		
		public event Action<PageOfLines> Page;
		
		
		private string _filename;
		
		public void Config(string filename)
		{
			_filename = filename;
		}
		
		
        internal static IEnumerable<string> Read_lines(string filename, long positionOfFirstLine, int numberOfLines)
        {
            using (var f = new FileStream(filename, FileMode.Open, FileAccess.Read)) {
                f.Seek(positionOfFirstLine, SeekOrigin.Begin);
                using (var r = new StreamReader(f, Encoding.UTF8))
                {
                    while(numberOfLines > 0 && !r.EndOfStream)
                    {
                        yield return r.ReadLine();
                        numberOfLines--;
                    }
                }
            }
        }
	}
}

